<template>
  <el-tag>{{ selectedValueLabel }}</el-tag>
</template>

<script setup lang="ts">
import { getDictOptions } from "@/api/dict";

const props = defineProps({
  /**
   * 字典类型编码(eg: 性别-gender)
   */
  typeCode: {
    type: String,
    required: true,
  },
  modelValue: {
    type: [String, Number],
    required: true,
  },
  dictData: {},
});

const options = ref<any>(); // 字典下拉数据源
const selectedValueLabel = ref<string | number | undefined>();

watch([options, () => props.modelValue], ([newOptions, newModelValue]) => {
  selectedValueLabel.value = newOptions[newModelValue];
});

onBeforeMount(async () => {
  let data: any = {};
  if (props.dictData) {
    data = props.dictData;
  } else {
    await getDictOptions(props.typeCode).then((response) => {
      data = response.data;
    });
  }
  let dict: any = {};
  for (const key in data) {
    let value: any = data[key];
    dict[value.value] = value.label;
  }
  options.value = dict;
});
</script>
